package com.banshuibao.bsb_android.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.BuildConfig;
import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.PersonalDataModel;
import com.banshuibao.bsb_android.uploadhead.ClipImageActivity;
import com.banshuibao.bsb_android.util.Base64ForImg;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.PictureUtil;
import com.banshuibao.bsb_android.util.XToast;

import java.io.File;

public class PersonalDataActivity extends PermissionBaseActivity implements View.OnClickListener {

    private ImageView mHeadImage, mBack;
    private EditText mEdit;
    private TextView mCommit;
    //原昵称
    private String name;
    //原头像名字
    private String imgName;
    //新昵称
    private String s;
    //新头像名字
    private String head;

    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //调用照相机返回图片文件
    private File tempFile;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        initView();
        getData();
    }

    private void getData() {
        name = getIntent().getStringExtra("name");
        imgName = getIntent().getStringExtra("imgName");
        if (!TextUtils.isEmpty(name)) {
            mEdit.setText(name);
            mEdit.setSelection(mEdit.getText().length());
        }
        if (!TextUtils.isEmpty(imgName)) {
            ImageUtil.loadImageHead(this, imgName, mHeadImage);
        }
    }

    private void initView() {
        mHeadImage = findViewById(R.id.image);
        mEdit = findViewById(R.id.edit);
        mBack = findViewById(R.id.back_personal);
        mCommit = findViewById(R.id.personal_commit);
        mCommit.setOnClickListener(this);
        mHeadImage.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                s = editable.toString();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(imgName)){
            if (!TextUtils.isEmpty(head) && !imgName.equals(head) || !TextUtils.equals(name,s)) {
                showPopupPrompt();
            } else {
                finish();
            }
        }else {
            if (!TextUtils.isEmpty(head) || !TextUtils.equals(name,s)) {
                showPopupPrompt();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null){
            popupWindow.dismiss();
        }
    }

    private void showPopupPrompt() {
        View view = View.inflate(this, R.layout.personal_data_popup, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        Button no = (Button) view.findViewById(R.id.popup_btn_no);
        Button yes = (Button) view.findViewById(R.id.popup_btn_yes);
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPost();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                finish();
            }
        });
        View parent = View.inflate(PersonalDataActivity.this, R.layout.activity_personal_data, null);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private void setPost() {
        GetLoginInfo loginInfo = GetLoginInfo.getLoginInfoInstance(this).readUser();
        String userId = loginInfo.getUserId();
        PersonalDataModel.body body = new PersonalDataModel.body();
        if (!TextUtils.isEmpty(userId)) {
            body.setUuid(userId);
        }
        if (TextUtils.isEmpty(s)) {
            XToast.showToast(this,"昵称不能为空");
            popupWindow.dismiss();
            return;
        }
        body.setName(s);
        if (!TextUtils.isEmpty(head)) {
            body.setHeadImg(head);
        }
        HttpUtil.doPost(Constants.Url.PERSONAL_DATA, body, new HttpResponse(this,PersonalDataModel.class) {
            @Override
            public void onResult(Object obj) {
                PersonalDataModel s = (PersonalDataModel) obj;
//                LogUtil.e(s);
//                PersonalDataModel.DataBean data = s.getData();
                finish();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_personal:
                if (!TextUtils.isEmpty(imgName)){
                    if (!TextUtils.isEmpty(head) && !imgName.equals(head) || !TextUtils.equals(name,s)) {
                        showPopupPrompt();
                    } else {
                        finish();
                    }
                }else {
                    if (!TextUtils.isEmpty(head) || !TextUtils.equals(name,s)) {
                        showPopupPrompt();
                    } else {
                        finish();
                    }
                }
                break;
            case R.id.image:
                GetHead(view);
                break;
            case R.id.personal_commit:
                setPost();
                break;
        }
    }

    private void GetHead(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow_two, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });

        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                requestUserPermission(v, Manifest.permission.CAMERA, REQUEST_CAPTURE);
                popupWindow.dismiss();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                requestUserPermission(v, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_PICK);
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void successGrantPermission(int requestCode) {
        switch (requestCode) {
            case REQUEST_CAPTURE:
                gotoCamera();
                break;
            case REQUEST_PICK:
                gotoPhoto();
                break;
        }
    }

    private void gotoPhoto() {
//     Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void gotoCamera() {
        //    Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");
        String authority = "com.banshuibao.bsb_android.fileprovider";
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置7.0中共享文件
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(PersonalDataActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    //      Log.e("TAG", "**********camera uri*******" + Uri.fromFile(tempFile).toString());
                    //       Log.e("TAG", "**********camera path*******" + getRealFilePathFromUri(RegisterActivity.this, Uri.fromFile(tempFile)));
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    //    Log.e("TAG", "**********pick path*******" + getRealFilePathFromUri(RegisterActivity.this, uri));
                    gotoClipActivity(uri);
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    Bitmap bitmap = BitmapFactory.decodeFile(cropImagePath);
                    //  writeSD(bitmap);
                    mHeadImage.setImageBitmap(PictureUtil.makeRoundCorner(bitmap));
                    //此处后面可以将bitMap转为二进制上传后台网络
                    //......
                    head = Base64ForImg.imgToBase64(cropImagePath);
                    // eum.setHeadImage(head);//修改头像
//                    body.setHeadImg(head);
                }
                break;
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        // Log.e("TAG", "**********clip path*******" + getRealFilePathFromUri(RegisterActivity.this, uri));
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", 1);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }


    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
